package com.BMS.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.BMS.Service.BookService;
import com.BMS.Service.UserService;
import com.BMS.entity.Book;
import com.BMS.entity.Borrow;
import com.BMS.entity.GiveBack;
import com.BMS.entity.Reader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;



/**
 * 图书实体类控制层
 * @author lenovo
 *
 */
@Controller
@RequestMapping("/Book")
public class BookController {

	private BookService bookService;
	private UserService userService;
	
	@Autowired
	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}
	
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	/*
	 * 图书数据渲染接口
	 * url:"/Book/showBook.do"
	 * 正确：返回code="200",bookList=bookList,pageCount=pageCount
	 * 错误：返回code="401",msg="暂无图书"
	 *     返回code="402",msg="当前页码错误",bookList=bookList,nowPage=1,pageCount=pageCount
	 *     返回code="403",msg="获取数据失败"
	 */
	@ResponseBody
	@RequestMapping(value="/showBook.do",method = RequestMethod.GET,produces={"application/json;charset=UTF-8"})
	public String ShowBook(HttpServletRequest request, HttpServletResponse response) {
		// 初始化JSON对象
		JSONObject obj = new JSONObject();
		
		// 获取参数
		// 排序字段
		String orderBy = request.getParameter("orderBy");
		// 当前页码
		int nowPage = Integer.parseInt(request.getParameter("nowPage"));
		
		// 初始化数据列表
		List<Book> bookList = null;
		
		// 获取总页码
		long pageCount = bookService.getPageCount();
		if(pageCount==0) {
			// 暂无数据
			obj.put("code", "401");
			obj.put("msg", "暂无图书数据");
			obj.put("pageCount", 0);
			return obj.toString();
		} else {
			// 有数据
			if(nowPage > pageCount) {
				// 当前页码错误
				bookList = bookService.findAllBooks(0, 10, orderBy);
				obj.put("bookList", JSON.toJSONString(bookList,true));
				obj.put("pageCount", JSON.toJSONString(pageCount,true));
				obj.put("nowPage", JSON.toJSONString(1,true));
				obj.put("code", "402");
				obj.put("msg", "当前页码错误！");
				return obj.toString();
			} else {
				// 页码正确
				bookList = bookService.findAllBooks(10*(nowPage-1), 10, orderBy);
				obj.put("bookList", JSON.toJSONString(bookList,true));
				obj.put("pageCount", JSON.toJSONString(pageCount,true));
				obj.put("code", "200");
				return obj.toString();
			}
		}
		
	}
	
	/*
	 * 图书更新控制层接口
	 * 接受前端ajax POST请求
	 * 返回json格式数据
	 * 正确：返回code="200",msg="更新成功"
	 * 错误：返回code="401",msg="图书不存在！"
	 * 
	 */
	@ResponseBody
	@RequestMapping(value="/bookUpdate.do",method=RequestMethod.POST,produces={"application/json;charset=UTF-8"})
	public String bookUpdate(Book book) {
		// 初始化JSON对象
		JSONObject obj = new JSONObject();
		
		// 查找该图书
		Book book1 = bookService.findBookById(book.getBook_ID());
		if(book1==null) {
			obj.put("code", "401");
			obj.put("msg", "该图书不存在！");
			return obj.toString();
		} else {
			bookService.updateBook(book);
			obj.put("code", "200");
			obj.put("msg", "更新成功！");
			return obj.toString();
		}
	}
	
	/*
	 * 图书删除功能控制层接口
	 * 接受前端ajax POST请求
	 * 返回json格式数据
	 * 正确：返回code="200",msg="删除成功"
	 * 错误：返回code="401",msg="图书不存在"
	 *     返回code="402",msg="下架失败"
	 */
	@ResponseBody
	@RequestMapping(value="/bookDel.do",method=RequestMethod.POST,produces={"application/json;charset=UTF-8"})
	public String bookDel(String book_id, String manager_id, String takeOff_date) {
		// 初始化JSON对象
		JSONObject obj = new JSONObject();
		
		// 查找图书
		Book book = bookService.findBookById(book_id);
		if(book==null) {
			obj.put("code", "401");
			obj.put("msg", "该图书不存在！");
			return obj.toString();
		} else {
			try {
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/M/d");
				Date date = sdf1.parse(takeOff_date);
				
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
				date = sdf2.parse(sdf2.format(date));
				bookService.takeOffBook(book_id, manager_id, date);
				obj.put("code", "200");
				obj.put("msg", "删除成功！");
				return obj.toString();
			} catch(Exception e) {
				e.printStackTrace();
				obj.put("code", "402");
				obj.put("msg", "图书无法下架！请检查该图书状态！");
				return obj.toString();
			}
			
		}
	}
	
	/*
	 * 图书上架功能控制层接口
	 * 接受前端ajax POST请求
	 * 返回json格式数据
	 * 正确：返回code="200",msg="添加图书信息成功！"
	 * 错误：返回code="401",msg="图书编号已存在！"
	 *     返回code="500",msg="服务器出错"
	 * 
	 */
	@ResponseBody
	@RequestMapping(value="/bookTakeOn.do",method=RequestMethod.POST,produces={"application/json;charset=UTF-8"})
	public String bookTakeOn(Book book, String manager_id, String takeOn_date) {
		// 初始化JSON对象
		JSONObject obj = new JSONObject();
		
		// 查找相同编号图书
		Book book1 = bookService.findBookById(book.getBook_ID());
		if(book1!=null) {
			// 图书编号已存在
			obj.put("code", "401");
			obj.put("msg", "图书编号已存在！");
			return obj.toString();
		} else {
			// 图书编号可用
			// 格式化日期
			try {
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/M/d");
				Date date = sdf1.parse(takeOn_date);
				
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
				date = sdf2.parse(sdf2.format(date));
				bookService.addBook(book, manager_id, date);
				obj.put("code", "200");
				obj.put("msg", "添加图书信息成功！");
				return obj.toString();
			} catch (ParseException e) {
				e.printStackTrace();
				obj.put("code","500");
				obj.put("msg", "服务器出错！");
				return obj.toString();
			}
			
		}
	}
	
	/*
	 * 图书下架功能控制层接口
	 * 接受前端ajax POST请求
	 * 返回json格式数据
	 * 正确：返回code="200",msg="下架成功"
	 * 错误：返回code="401",msg="图书不存在"
	 *     返回code="500",msg="服务器出错"
	 */
	@ResponseBody
	@RequestMapping(value="/bookTakeOff.do",method=RequestMethod.POST,produces={"applictioin/json;charset=UTF-8"})
	public String bookTakeOff(String book_id, String manager_id, String takeOff_date) {
		// 初始化JSON对象
		JSONObject obj = new JSONObject();
		
		// 检查图书是否存在
		Book book = bookService.findBookById(book_id);
		if(book==null) {
			// 不存在
			obj.put("code", "401");
			obj.put("msg", "图书不存在！");
			return obj.toString();
		} else {
			// 存在
			// 格式化日期
			try {
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/M/d");
				Date date = sdf1.parse(takeOff_date);
			
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
				date = sdf2.parse(sdf2.format(date));
			
				bookService.takeOffBook(book_id, manager_id, date);
				obj.put("code", "200");
				obj.put("msg", "图书下架成功！");
				return obj.toString();
			} catch (ParseException e) {
				e.printStackTrace();
				obj.put("code", "500");
				obj.put("msg", "服务器出错！");
				return obj.toString();
			}
		}
	}
	
	/*
	 * 图书查询控制类
	 * 接受前端ajax GET请求
	 * 返回json格式数据
	 * 正确：返回book信息，code="200"
	 * 错误：返回code="400"，msg="图书不存在"
	 * 		
	 * 
	 */
	@RequestMapping(value="/bookSearch.do",method=RequestMethod.GET,produces={"application/json;charset=UTF-8;"})
	@ResponseBody
	public String SearchBook(HttpServletRequest request, HttpServletResponse response) {
		
		
		JSONObject obj = new JSONObject();
		
		
		// 获取输入图书ID
		String book_id = request.getParameter("book_id");
		
		Book book = null;
		book = bookService.findBookById(book_id);
		
		if(book!=null) {
			// 图书存在
			// 获取图书借阅信息
			if(bookService.isBorrowable(book_id)) {
				// 图书可借阅
				obj.put("status", true);
			} else {
				// 图书已被借阅
				Borrow borrow = bookService.findBorrowByBookId(book_id);
				String reader_id = borrow.getReader_ID();
				Date borrow_date = borrow.getBorrow_date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				
				obj.put("status", false);
				obj.put("reader_id", reader_id);
				obj.put("borrow_date", df.format(borrow_date));
			}
			obj.put("book", JSON.toJSONString(book,true));
			obj.put("code", "200");
		} else {
			obj.put("code", "400");
			obj.put("msg", "图书不存在！");
		}
		
		return obj.toString();
		
		//System.out.println(book.getTitle());
	}
	
	/*
	 * 图书借阅控制层接口
	 * 接受前端ajax POST请求
	 * 返回json格式数据
	 * 正确：返回code="200"
	 * 错误：返回code="401" - 读者ID不存在
	 *     返回code="402" - 图书ID不存在
	 *     返回code="403" - 图书已被借阅
	 *     返回code="500" - 操作失败
	 *     
	 */
	@ResponseBody
	@RequestMapping(value="/bookBorrow.do",method=RequestMethod.POST,produces={"application/json;charset=UTF-8"})
	public String BorrowBook(HttpServletRequest request, HttpServletResponse response) {
		// 生成json对象
		JSONObject obj = new JSONObject();
		// 获取输入读者ID
		String reader_id = request.getParameter("reader_id");
		// 检查读者ID是否存在
		Reader reader = userService.findReaderById(reader_id);
		if(reader==null) {
			// 读者ID不存在
			obj.put("code", "401");
			obj.put("msg", "读者ID不存在!");
			return obj.toString();
		}
		// 获取输入图书ID
		String book_id = request.getParameter("book_id");
		// 检查图书ID是否存在
		Book book = bookService.findBookById(book_id);
		if(book==null) {
			// 图书ID不存在
			obj.put("code", "402");
			obj.put("msg", "图书ID不存在！");
			return obj.toString();
		} else if(bookService.isBorrowable(book_id)==false) {
			obj.put("code", "403");
			obj.put("msg", "图书已被借阅！");
			return obj.toString();
		} else {
			try {
				// 获取管理员ID
				String manager_id = request.getParameter("manager_id");
				// 获取借阅日期
				String date = request.getParameter("borrow_date");
				
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/M/d");
				Date borrow_date = sdf1.parse(date);
				
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
				borrow_date = sdf2.parse(sdf2.format(borrow_date));
				
				// 封装borrow对象
				Borrow borrow = new Borrow();
				borrow.setReader_ID(reader_id);
				borrow.setManager_ID(manager_id);
				borrow.setBook_ID(book_id);
				borrow.setBorrow_date(borrow_date);
				// 保存borrow实例
				bookService.addBorrow(borrow);
				// 成功保存
				obj.put("code", "200");
				obj.put("msg", "借阅成功！");
				return obj.toString();
			} catch (Exception e) {
				obj.put("code", "500");
				obj.put("msg", "操作失败！");
				e.printStackTrace();
				return obj.toString();
			}
		}
		
	}
	
	
	/*
	 * 图书归还控制层接口
	 * 接受前端ajax POST请求
	 * 返回json格式数据
	 * 正确：返回code="200"
	 * 错误：返回code="401" - 图书未被借阅
	 *     返回code="500" - 操作失败
	 */
	@ResponseBody
	@RequestMapping(value="/bookReturn.do",method=RequestMethod.POST,produces={"application/json;charset=UTF-8"})
	public String BookReturn(HttpServletRequest request, HttpServletResponse response) {
		// 初始化json对象
		JSONObject obj = new JSONObject();
		
		
		try {
			// 获取参数
			String book_id = request.getParameter("book_id");
			if(bookService.isBorrowable(book_id)) {
				obj.put("code", "401");
				obj.put("msg", "图书未被借阅！");
				return obj.toString();
			} else {
				String reader_id = request.getParameter("reader_id");
				String manager_id = request.getParameter("manager_id");
				
				String date = request.getParameter("giveback_date");
				
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/M/d");
				Date giveBack_date = sdf1.parse(date);
				
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
				giveBack_date = sdf2.parse(sdf2.format(giveBack_date));
				
				// 封装GiveBack对象
				GiveBack giveBack = new GiveBack();
				giveBack.setReader_ID(reader_id);
				giveBack.setManager_ID(manager_id);
				giveBack.setBook_ID(book_id);
				giveBack.setGiveBack_date(giveBack_date);
				// 保存归还记录
				bookService.addGiveBack(giveBack);
				// 保存成功
				obj.put("code", "200");
				obj.put("msg", "归还成功！");
				return obj.toString();
				
			}
		} catch (ParseException e) {
			obj.put("code", "500");
			obj.put("msg", "操作失败");
			e.printStackTrace();
			return obj.toString();
		}
		
	}
	
	/*
	 * 数据绑定初始化方法
	 * 将前台传入的日期（字符串）类型转换为Date类型
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		
		// true:允许为空; false:不允许为空
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,true));
	}
}
